//
//  DatabaseTool.m
//  CHENGER
//
//  Created by mac on 16/11/24.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "DatabaseTool.h"
#import "People.h"

@implementation DatabaseTool
+(void)opendataandcreatetable{

    NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"database.sqlite"];
    _DB=[[FMDatabase alloc]initWithPath:path];
    BOOL isOpen = [_DB open];
    if(isOpen==YES)
    {
        NSLog(@"打开成功");
    }else{
        NSLog(@"打开失败");
    }

    if ([_DB open]) {

        NSString *sql=@"create table if not exists People (peopleID integer primary key autoincrement not null unique,name text)";
        [_DB executeUpdate:sql];

        NSString *sql1=@"create table if not exists Phone(PeopleID integer not null,phone text)";
        [_DB executeUpdate:sql1];
    }



}
+(NSArray *)getallcontact{

NSString *sql=@"select * from People";
    FMResultSet *set=[_DB executeQuery:sql];

    NSMutableArray *array=[NSMutableArray array];
    while ([set next]) {
        People *pp=[[People alloc]init];
       pp.name=[set stringForColumnIndex:1];
        pp.peopleID=[set intForColumnIndex:0];


        [array addObject:pp];
        
    }
    [set close];
    return array;

}
+(NSArray *)getallphonewithpeopleid:(NSInteger)peopleID{


    NSString *sql=[NSString stringWithFormat: @"select * from Phone where peopleID=%ld",peopleID ];
    FMResultSet *set=[_DB executeQuery:sql];

    NSMutableArray *array=[NSMutableArray array];
    while ([set next]) {
        NSString * phone=[set stringForColumnIndex:1];
        [array addObject:phone];
    }
    [set close];
    return array;

}
+(NSInteger)insertcontactWithName:(NSString *)name{
    NSString *sql=[NSString stringWithFormat:@"insert into People (name) values('%@')",name];
    [_DB executeUpdate:sql];

    sql=@"select max (peopleID) from People";
    FMResultSet *set=[_DB executeQuery:sql];

    [set next];
    NSInteger peopleID=[set intForColumnIndex:0];
    [set close];
    return  peopleID;

}
+(void)insertPhoneWithPeopleID:(NSInteger)peopleID phone:(NSString *)phone{
    NSString *sql=[NSString stringWithFormat:@"insert into Phone(peopleID,phone ) values (%ld,'%@')",peopleID,phone];
    [_DB executeUpdate:sql];



}















@end
